﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QuickApp.Core;
using EfSearchModel.Model;
using System.Data.Entity.Validation;
using QuickApp.MVCControl.Tree;
using Resto.CostControl.Core.Models.SysSettings;
using QuickApp.MVCControl;
using Resto.CostControl.Core;
using System.Globalization;
using QuickApp.MVCControl.Form;

namespace Resto.CostControl.Web.Controllers
{
    public class WeekDishOrderController : Controller
    {
        // 为了明天的演示，先写死项目点，后续改为当前用户所属的项目点
        private readonly string SiteId = "457930f4-2356-43e5-9e75-e8dfee27e288";
        private readonly IRepository<WeekDishOrder> _Repo;
        private readonly IRepository<DishOrderItem> _RepoItem;
        private readonly IUnitOfWork _UnitOfWork;

        public WeekDishOrderController(IRepository<WeekDishOrder> repo, IRepository<DishOrderItem> repoItem, UnitOfWork unitOfWork)
        {
            _Repo = repo;
            _RepoItem = repoItem;
            _UnitOfWork = unitOfWork;
        }

        [Ninject.Inject]
        public IRepository<EnumItem> ItemRepo { get; set; }

        [HttpPost]
        public JsonResult Tree(string type,string datetime = null)
        {
            var nodes = new List<JsonTreeNode>();
            var items = ItemRepo.FindAll(item => item.TypeCode == "MealType").OrderBy(item => item.SeqNo).Select(item => new { item.EnumCode, item.EnumName });
            var weeks = ItemRepo.FindAll(item => item.TypeCode == "Week").OrderBy(item => item.SeqNo).Select(item => new { item.EnumCode, item.EnumName });
            Action<List<JsonTreeNode>, string, string> BuildChildrenNodes = (cNodes, weekdate, week) =>
            {
                foreach (var item in items)
                {
                    var node = new JsonTreeNode();
                    node.id = weekdate + "#" + item.EnumCode;
                    node.text = item.EnumName;
                    node.value = week + "——" + item.EnumName;
                    node.isexpand = true;
                    node.showcheck = false;
                    node.complete = true;
                    node.hasChildren = false;
                    cNodes.Add(node);
                }
            };
            var CurrentDate = DateTime.Now.AddDays(7);
            if (!string.IsNullOrEmpty(datetime))
            {
                CurrentDate = Convert.ToDateTime(datetime);
            }
            var dayOfWeek = (double)CurrentDate.DayOfWeek;
            foreach (var week in weeks)
            {
                dayOfWeek = dayOfWeek == 0 ? 7 : dayOfWeek;
                var date = CurrentDate.AddDays(double.Parse(week.EnumCode) - dayOfWeek).ToString("yyyy-MM-dd");

                var node = new JsonTreeNode();
                node.id = date;
                node.text = date + string.Format("（{0}）", week.EnumName);
                node.value = date + string.Format("（{0}）", week.EnumName);
                node.isexpand = true;
                node.showcheck = false;
                node.complete = true;
                node.hasChildren = true;
                if (date == DateTime.Now.ToString("yyyy-MM-dd"))
                {
                    node.checkstate = 0;
                }
                BuildChildrenNodes(node.ChildNodes, date, node.text);
                nodes.Add(node);
            }

            return Json(nodes);
        }

        [HttpPost]
        public JsonResult List(string type, DWZPageInfo pager, DWZQueryModel where)
        {
            // 添加ParentId的检索条件
            if (!string.IsNullOrWhiteSpace(type))
            {
                var args = type.Split('#');
                where.AddItem("Date", args[0], QueryMethod.DateBlock);
                if (args.Length == 2)
                {
                    where.AddItem("MealType", args[1]);
                }
            }
            else
            {
                where.AddItem("Date", DateTime.Now.ToString("yyyy-MM-dd"), QueryMethod.DateBlock);
            }

            // 分页查询数据
            var list = _RepoItem.GetPageable(pager.ToPageInfo(), where);
            var fdata = pager.ToFlexiGridData<DishOrderItem>(list.Page.ToList(), list.Total);

            return Json(fdata);
        }

        public ActionResult Index()
        {
            ViewBag.SelectWeek = CommonController.GetWeekOfYear(DateTime.Now.AddDays(7));
            ViewBag.WeekList = GetWeekDataSource();
            ViewBag.DefaultDate = DateTime.Now.AddDays(7).ToString("yyyy-MM-dd");
            return View();
        }

        public ActionResult Edit(string Id, string type)
        {
            DishOrderItem data = null;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                data = _RepoItem.Find(Id);
            }
            else
            {
                data = new DishOrderItem();
                data.SiteId = SiteId;
                if (!string.IsNullOrWhiteSpace(type))
                {
                    var args = type.Split('#');
                    data.Date = DateTime.Parse(args[0]);
                    if (args.Length == 2)
                    {
                        data.MealType = args[1];
                    }
                }
                else
                {
                    data.Date = DateTime.Now;
                }
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult Save(DishOrderItem data)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var orderId = "";
                    //data.Date = DateTime.Now;
                    
                    var week = CommonController.GetWeekOfYear(data.Date);
                    var weekDish = _Repo.FindAll(d => d.Week == week);
                    if (weekDish.Count() == 0)
                    {
                        WeekDishOrder wDish = new WeekDishOrder();
                        wDish.SiteId = "93507f1c-aa08-4a9a-b2b4-303385e040b5";
                        wDish.ReportDate = DateTime.Now;
                        wDish.ReportUserName = "管理员";
                        wDish.Code = "w" + data.Date.Month.ToString().PadLeft(2, '0') + data.Date.Date.ToString().PadLeft(2, '0');
                        wDish.Name = data.Date.Month.ToString() + "月第" + week + "周" + wDish.SiteName;
                        wDish.Week = week;
                        wDish.BeginDate = CommonController.GetWeekDay(data.Date.Year, week, 0);
                        wDish.EndDate = CommonController.GetWeekDay(data.Date.Year, week, 6);
                        orderId = Guid.NewGuid().ToString();
                        wDish.Id = orderId;
                        _Repo.Insert(wDish);

                    }
                    else
                    {
                        orderId = weekDish.FirstOrDefault().Id;
                    }

                    if (string.IsNullOrWhiteSpace(data.Id))
                    {
                        data.Week = week;
                        data.Id = Guid.NewGuid().ToString();
                        //新增时，订单状态默认暂存
                        data.OrderId = orderId;
                        _RepoItem.Insert(data);
                    }
                    else
                    {
                        data = _RepoItem.Find(data.Id);
                        data.Week = week;
                        TryUpdateModel(data);
                    }

                    _UnitOfWork.Commit();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            var result = new JsonReturnMessages
            {
                IsSuccess = true,
                Msg = "操作成功",
            };
            return Json(result);
        }

        [HttpPost]
        public JsonResult DeleteItem(string Id)
        {
            var result = new JsonReturnMessages
            {
                IsSuccess = true,
                Msg = "操作成功",
            };
            return Json(result);
        }

        public List<SelectListItem> GetWeekDataSource()
        {
            var date = DateTime.Now;
            var year = date.Year;
            var items = new List<SelectListItem>();
            var weeks = CommonController.GetWeekAmount(year);
            var curweek = CommonController.GetWeekOfYear(date) + 1;
            for (var i = 1; i <= weeks; i++)
            {
                var startDay = CommonController.GetWeekDay(year, i, 1);
                var endDay = CommonController.GetWeekDay(year, i, 7);
                items.Add(new SelectListItem
                {
                    Text = "(" + i.ToString().PadLeft(2, '0') + "周)" + startDay.ToString("MM-dd") + "—" + endDay.ToString("MM-dd"),
                    Value = Url.Action("Index", new { week = i, day = startDay.ToString("yyyy-MM-dd") }),
                });
            }
            return items;
        }

        public ActionResult Reported(int week)
        {
            WeekDishOrder data = _Repo.Find(d => d.Week == week);
            if (data == null)
            {
                throw new Exception("请先输入订单明细");
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult Reported(WeekDishOrder data)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var olddata = _Repo.Find(data.Id);
                    TryUpdateModel(olddata);
                    _UnitOfWork.Commit();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            var result = new JsonReturnMessages
            {
                IsSuccess = true,
                Msg = "操作成功",
            };
            return Json(result);
        }
    }
}